package com.apes.scm.masterdata.product.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.product.model.OrientationDiagramCategory;
import com.apes.scm.masterdata.product.model.OrientationDiagramMenu;
import com.apes.scm.masterdata.product.repository.OrientationDiagramCategoryRepository;
import com.apes.scm.masterdata.product.repository.OrientationDiagramMenuRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service("orientationDiagramCategoryService")
public class OrientationDiagramCategoryService extends DomainService {

    @Autowired
    OrientationDiagramMenuRepository orientationDiagramMenuRepository;
    @Autowired
    OrientationDiagramCategoryRepository orientationDiagramCategoryRepository;
    @Autowired
    SequenceService sequenceService;
    /**
     * 创建
     */
    public OrientationDiagramCategory create(SimpleRequest request) {

        OrientationDiagramCategory diagramCategory = request.getO(OrientationDiagramCategory.class);

        if (diagramCategory.getId() == null || diagramCategory.getId().equals("")){
            diagramCategory.setId(sequenceService.getId(OrientationDiagramCategory.CONST_TABLE_NAME));
        }


        // 校验数据
        checkExists(diagramCategory);

        // 将临时字段设置为原始字段
        diagramCategory.setMenu(diagramCategory.getTempMenu());


        OrientationDiagramMenu menu = orientationDiagramMenuRepository.findOne(diagramCategory.getTempMenu().getId());

        menu.getCategories().add(diagramCategory);

        // 保存主表
        orientationDiagramMenuRepository.saveAndFlush(menu);

        return menu.getCategories().stream()
                .filter(orientationDiagramCategory -> orientationDiagramCategory.getCategory().getId().equals(diagramCategory.getCategory().getId())).findFirst().orElse(null);
    }


    /***
     * 修改
     */
    public OrientationDiagramCategory update(SimpleRequest request) {

        OrientationDiagramCategory diagramCategory = request.getO(OrientationDiagramCategory.class);

        // 校验数据
        checkExists(diagramCategory);

        // 将临时字段设置为原始字段
        diagramCategory.setMenu(diagramCategory.getTempMenu());

        OrientationDiagramMenu menu = orientationDiagramMenuRepository.findOne(diagramCategory.getTempMenu().getId());

        // 删除选中行
        Iterator<OrientationDiagramCategory> iterator = menu.getCategories().iterator();
        while(iterator.hasNext()){
            OrientationDiagramCategory item = iterator.next();
            if(item.getId().equals(diagramCategory.getId())) {
                iterator.remove();
            }
        }
        // 添加更新行
        menu.getCategories().add(diagramCategory);

        // 保存主表
        orientationDiagramMenuRepository.saveAndFlush(menu);

        return menu.getCategories().stream()
                .filter(orientationDiagramCategory -> orientationDiagramCategory.getCategory().getId().equals(diagramCategory.getCategory().getId())).findFirst().orElse(null);

    }

    /***
     * 删除
     */
    public String delete(SimpleRequest request) {

        OrientationDiagramCategory diagramCategory = request.getO(OrientationDiagramCategory.class);

        OrientationDiagramMenu menu = orientationDiagramMenuRepository.findOne(diagramCategory.getTempMenu().getId());


        Iterator<OrientationDiagramCategory> iterator = menu.getCategories().iterator();

        // 删除选中行
        while(iterator.hasNext()){
            OrientationDiagramCategory item = iterator.next();
            if(item.getId().equals(diagramCategory.getId())) {
                iterator.remove();
            }
        }

        orientationDiagramMenuRepository.saveAndFlush(menu);

        return "删除成功";
    }

    /***
     * 验证数据已存在
     */
    private void checkExists(OrientationDiagramCategory diagramCategory) {

        OrientationDiagramCategory exists = orientationDiagramCategoryRepository.findOne(JpaDsl.toCriteriaIgnoreNull(
                "category.id", "EQ", diagramCategory.getCategory().getId(),
                "menu.id", "EQ", diagramCategory.getTempMenu().getId(),
                "id", "NE", diagramCategory.getId()
         )).orElse(null);

        if (exists != null) throw new RuntimeException("当前配件名称在当前目录已有数据");

    }

    /***
     * 导入数据
     */
    private void importData(SimpleRequest request) {

        JSONObject tempJson = request.getJO();
        if (tempJson.get("items") == null || tempJson.getJSONArray("items").size() == 0){
            throw new RuntimeException("导入数据为空，请查证");
        }


        tempJson.getJSONArray("items").stream().forEach(json -> {
            JSONObject item = (JSONObject) json;

            JSONObject diagramCategoryJson = new JSONObject();
            diagramCategoryJson.put("tempMenu", item.getJSONObject("orientationDiagramMenu"));
            diagramCategoryJson.put("category", item.getJSONObject("category"));
            diagramCategoryJson.put("specialUse", item.getIntValue("specialUse"));

            request.setData(diagramCategoryJson);

            try {
                create(request);
            } catch (Exception e) {

            }
        });

    }
}
